package com.cy.ppj.service.wechat.impl;

import com.cy.ppj.comm.constant.CacheConstants;
import com.cy.ppj.comm.utils.JsonObjectMapper;
import com.cy.ppj.comm.utils.SpringContextUtils;
import com.cy.ppj.model.Result;
import com.cy.ppj.model.dto.wechat.WechatMessageTemplateDTO;
import com.cy.ppj.service.BaseService;
import com.cy.ppj.service.wechat.BankmaWechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 马先生社区微信公众号 api 服务
 * @Author tanyilin
 * @Date 2019/4/3 16:38
 */
@Slf4j
@Service
public class BankmaWechatServiceImpl extends BaseService implements BankmaWechatService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${bankma.wechat.app-id}")
    private String appId;
    @Value("${bankma.wechat.secret}")
    private String secret;
    @Value("${wecaht.access-token.url}")
    private String accessTokenUrl;
    @Value("${wechat.template.send.url}")
    private String templateSendUrl;


    @Override
    @Cacheable(value = CacheConstants.CACHE_VALUE_1H)
    public String getBaseAccessToken() {

        //组装参数
        Map<String, String> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", secret);

        //发送请求获取token
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(accessTokenUrl, String.class, params);
        state(HttpStatus.OK.equals(responseEntity.getStatusCode()), "获取TOKEN失败");
        Map<String, String> map = JsonObjectMapper.read(responseEntity.getBody(), Map.class);
        log.info("请求微信access_token回调: {}", map);
        String token = map.get("access_token");
        state(StringUtils.hasLength(token), "获取TOKEN失败");
        return token;
    }

    @Override
    public Result sendTemplateMessage(WechatMessageTemplateDTO wechatMessageTemplateDTO) {

        String openId = wechatMessageTemplateDTO.getOpneId();
        String json = JsonObjectMapper.toJson(wechatMessageTemplateDTO);

        //发送微信模板消息
        log.info("给客户【{}】发送微信消息模版请求报文 requestData： {}", openId, json);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> httpEntity = new HttpEntity<>(json, headers);

        //获取微信accessToken
        String accessToken = SpringContextUtils.getBean(BankmaWechatService.class).getBaseAccessToken();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(templateSendUrl, httpEntity, String.class, accessToken);

        if(!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
            return Result.fail("发送微信消息模版请求失败");
        }

        log.info("给客户【{}】发送微信消息模版回调报文 responseData： {}", openId, responseEntity.getBody());

        String responseBody = responseEntity.getBody();
        Map<String, Object> result = JsonObjectMapper.read(responseBody, Map.class);
        Integer errcode = (Integer) result.get("errcode");
        if (!Integer.valueOf(0).equals(errcode)) {
            return Result.fail("发送微信消息模版失败");
        }

        return Result.success();
    }


}
